{% extends 'base.html' %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">运行中心</h1>
</div>
{% if ok is not none %}
  {% if ok == '1' %}
    <div class="alert alert-success">{{ msg }}</div>
  {% else %}
    <div class="alert alert-danger">{{ msg }}</div>
  {% endif %}
{% endif %}

<!-- 仪表盘卡片：队列情况（保留），不显示“运行状态/最近一轮”卡片 -->
<div class="row g-3 mb-3">
  <div class="col-md-4">
    <div class="card h-100"><div class="card-body">
      <div class="text-secondary">待处理队列</div>
      <div class="display-6" id="queuePending">{{ queue_pending }}</div>
    </div></div>
  </div>
  <div class="col-md-4">
    <div class="card h-100"><div class="card-body">
      <div class="text-secondary">进行中</div>
      <div class="display-6" id="queueRunning">{{ queue_running }}</div>
    </div></div>
  </div>
  <div class="col-md-4">
    <div class="card h-100"><div class="card-body">
      <div class="text-secondary">失败累计</div>
      <div class="display-6" id="queueFailed">{{ queue_failed }}</div>
    </div></div>
  </div>
</div>

<div class="card mb-3">
  <div class="card-body">
    <div class="row g-3 align-items-end">
      <div class="col-md-5">
        <div class="form-label">将处理的邮箱（已启用）</div>
        <div class="form-text">
          {% if enabled_mailboxes %}
            {% for m in enabled_mailboxes %}
              <span class="badge text-bg-secondary me-1">{{ m.name }}</span>
            {% endfor %}
          {% else %}
            <span class="text-danger">暂无启用的邮箱</span>
          {% endif %}
        </div>
      </div>
      <div class="col-md-7">
        <form action="/run/daemon/start" method="post" class="row g-3 align-items-end">
          {% csrf_token %}
          <div class="col-md-3">
            <label for="interval" class="form-label">轮询间隔（秒）</label>
            <input type="number" class="form-control" id="interval" name="interval" value="{{ interval }}" min="5" max="3600">
          </div>
          <div class="col-md-3">
            <label for="workers" class="form-label">处理线程数</label>
            <input type="number" class="form-control" id="workers" name="workers" value="{{ workers }}" min="1" max="32">
          </div>
          <div class="col-md-3">
            <label for="limit" class="form-label">每邮箱拉取</label>
            <input type="number" class="form-control" id="limit" name="limit" value="{{ limit }}" min="1" max="200">
            <div class="form-text">范围 1-200 封</div>
          </div>
          <div class="col-md-3 d-flex align-items-end justify-content-end gap-2">
            <button id="btnStartDaemon" type="submit" class="btn btn-primary" {% if is_running %}disabled{% endif %}>启动</button>
            <button id="btnStopDaemon" type="submit" class="btn btn-danger" formaction="/run/daemon/stop" {% if not is_running %}disabled{% endif %}>停止</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-body">
    <form action="/run/start" method="post">
      {% csrf_token %}
      <div class="row g-3 align-items-end">
        <div class="col-md-3">
          <label for="limit_once" class="form-label">手动：每个邮箱拉取最近</label>
          <input type="number" class="form-control" id="limit_once" name="limit" value="20" min="1" max="200">
          <div class="form-text">范围 1-200 封</div>
        </div>
        <div class="col-md-3">
          <button type="submit" class="btn btn-secondary">手动执行一轮</button>
          <a href="/runs" class="btn btn-outline-secondary ms-2">查看运行记录</a>
        </div>
      </div>
    </form>
  </div>
</div>

<script>
(function(){
  function makeWsUrl(path, hostOverride){
    var proto = (location.protocol === 'https:') ? 'wss' : 'ws';
    var host = hostOverride || location.host; // e.g. 127.0.0.1:8000
    return proto + '://' + host + path;
  }
  function altPortHost(){
    var hn = location.hostname; // no port
    var port = '8001'; // Daphne 默认端口（已在本地启动）
    return hn + ':' + port;
  }
  function setText(id, val){
    var el = document.getElementById(id);
    if(el){ el.textContent = val; }
  }
  function setRunning(running){
    var btnStart = document.getElementById('btnStartDaemon');
    var btnStop = document.getElementById('btnStopDaemon');
    if(btnStart){ btnStart.disabled = !!running; }
    if(btnStop){ btnStop.disabled = !running; }
  }

  var endpoints = [
    makeWsUrl('/ws/run_center/'),
    makeWsUrl('/ws/run_center/', altPortHost())
  ];
  var lastGoodIndex = 0; // 记住上次成功端点
  var reconnectDelay = 1000;

  function connect(attemptIndex){
    var idx = (typeof attemptIndex === 'number') ? attemptIndex : lastGoodIndex;
    if(idx < 0 || idx >= endpoints.length) idx = 0;
    var url = endpoints[idx];
    var ws = new WebSocket(url);
    var triedFallback = false;

    ws.onopen = function(){
      lastGoodIndex = idx;
      reconnectDelay = 1000;
    };
    ws.onmessage = function(ev){
      try {
        var data = JSON.parse(ev.data);
        if(typeof data.queue_pending !== 'undefined') setText('queuePending', data.queue_pending);
        if(typeof data.queue_running !== 'undefined') setText('queueRunning', data.queue_running);
        if(typeof data.queue_failed !== 'undefined') setText('queueFailed', data.queue_failed);
        if(typeof data.is_running !== 'undefined') setRunning(!!data.is_running);
      } catch(e){}
    };
    ws.onerror = function(){
      // 连接错误时，优先尝试另一个端点一次
      if(!triedFallback){
        triedFallback = true;
        var alt = (idx === 0) ? 1 : 0;
        try { ws.close(); } catch(e){}
        setTimeout(function(){ connect(alt); }, 200);
        return;
      }
      try { ws.close(); } catch(e){}
    };
    ws.onclose = function(){
      // 正常重连到最近成功的端点
      setTimeout(function(){ connect(lastGoodIndex); }, reconnectDelay);
      reconnectDelay = Math.min(10000, reconnectDelay * 2);
    };
  }

  if('WebSocket' in window){ connect(); }
})();
</script>
{% endblock %}